<template>
	<view>
		<view class="circle">
			<!-- <view class="houseId row-center">
				{{show_nfcId ? '鸽舍号：'+ show_nfcId : '鸽舍号'}}
			</view> -->
			<view class="tip" v-if="tip !== 0">下一个鸽舍为：<span>{{tip}}</span>号鸽舍</view>
			<view v-else class="tip">当前鸽笼已全部处理完成</view>
			<proportion :leftValue="stayCount" :rightValue="whipCount"></proportion>
			
			<!-- 数据加载状态 -->
			<view v-if="isLoading" class="loading-data">
				<u-loading mode="circle" size="40"></u-loading>
				<text>数据加载中...</text>
			</view>
			
			<!-- 有数据时显示 -->
			<view v-else-if="cageStatu && cageStatu.length" class="ul">
				<view class="li" v-for="(item, index) in cageStatu" :key="`cage-item-${item.cage_id}-${index}`">
					<view class="left">
						<span class="cageId">{{item.cage_id}}</span>
						<span class="statu">{{item.statu}}</span>
					</view>
					<view class="right" v-if="stayNum.length > 0">
						<button 
							class="num" 
							v-for="item_child in numList" 
							:key="`cage-${item.cage_id}-num-${item_child}`"
							@click="handleClick(item.cage_id,item_child)"
							:class="getButtonClass(item.cage_id, item_child)"
							:disabled="isSubmitting"
						>
							{{item_child}}
						</button>
					</view>
				</view>
			</view>
			
			<!-- 无数据状态 -->
			<view v-else-if="cageStatu && cageStatu.length === 0" class="no-data">
				<text>暂无数据</text>
			</view>
		</view>
		<!-- 顶部提示 -->
		<u-toast ref="uToast" />
		<!-- 加载状态 -->
		<u-loading v-if="isLoading"></u-loading>
	</view>
</template>

<script>
	import {
		reqPutEggs,
		reqGetStatu,
		reqPutTips,
		reqStayNum
	} from '@/api/index.js'
	import {
		getNowDate
	} from '@/getTime.js'
	import {
		mapGetters
	} from 'vuex'
	import {
		debounce
	} from '@/utils/debounce.js'
	import { format } from '@/utils/format_HouseId.js'
	
	export default {
		data() {
			return {
				baseFormData: {
					siteId: '',
					houseId: '',
					cageId: '',
					putNumber: 4,
					putTime: null,
					cageStatu: '带仔中'
				},
				numList: [1,2,3,4],
				stayNum: [],
				statu: [],
				flag: true,
				tip: '',
				cancelToken: {
					cancelToken: true
				},
				cancel: '',
				isLoading: false,
				isSubmitting: false,
				debounceGetTips: debounce(() => {
					this.getTips()
				}, 200)
			};
		},
		
		// 修改 mounted 生命周期
		async mounted() {
			this.isLoading = true;
			try {
				await this.getStatu();      // 获取鸽笼状态
				await this.debounceGetTips();
				await this.getStay();
				await this.getPR();
			} catch (error) {
				console.error('mounted hook error:', error);
				this.$refs.uToast.show({
					title: '初始化失败: ' + (error.message || '未知错误，没获取到鸽笼信息'),
					type: 'error',
					duration: 2000,
					position: 'top'
				});
			} finally {
				this.isLoading = false;
			}
		},
		
		watch: {
			// 监听当前的nfcId，一旦改变就重新获取鸽笼状态
			async nfcId(newValue, oldValue) {
				if (newValue !== oldValue) {
					console.log('监听到前后值不一样，发送请求');
					this.isLoading = true;
					try {
						await this.getStatu();      // 获取鸽笼状态
						await this.debounceGetTips();
						await this.getStay();
					} catch (error) {
						console.error('nfcId watch error:', error);
						this.$refs.uToast.show({
							title: '数据更新失败',
							type: 'error',
							duration: 2000,
							position: 'top'
						});
					} finally {
						this.isLoading = false;
					}
				}
			}
		},
		
		computed: {
			...mapGetters(['nfcId', 'show_nfcId', 'cageStatu', 'loading','whipCount','stayCount'])
		},
		
		methods: {
			// 获取鸽笼状态（与查蛋页面相同的方法）
			async getStatu() {
				console.log('放仔页面 - 获取鸽笼状态');
				const obj = {
					siteId: uni.getStorageSync('siteId'),
					houseId: this.nfcId,
				}
				console.log('获取鸽笼状态参数:', obj);
				await this.$store.dispatch('getStatu', obj);
			},
			
			// 修复：安全获取按钮样式类的方法
			getButtonClass(cageId, number) {
				if (!this.stayNum || !Array.isArray(this.stayNum)) {
					return '';
				}
				
				// 安全获取对应的stayNum项
				const cageIndex = cageId - 1;
				if (cageIndex < 0 || cageIndex >= this.stayNum.length) {
					console.warn(`cageId ${cageId} 超出 stayNum 数组范围`);
					return '';
				}
				
				const cageData = this.stayNum[cageIndex];
				if (!cageData) {
					console.warn(`cageId ${cageId} 对应的数据为 undefined`);
					return '';
				}
				
				// 安全获取number属性
				const cageNumber = cageData.number;
				if (cageNumber === undefined || cageNumber === null) {
					console.warn(`cageId ${cageId} 的number属性为 undefined 或 null`);
					return '';
				}
				
				// 比较数字
				return number === cageNumber ? 'ycd_button_right' : '';
			},
			
			// 检查必要的依赖数据
			async checkDependencies() {
				if (!this.nfcId) {
					throw new Error('NFC ID 未设置，请先读取NFC标签');
				}
				
				const siteId = uni.getStorageSync('siteId');
				if (!siteId) {
					throw new Error('站点ID未找到，请重新登录');
				}
				this.baseFormData.siteId = siteId;
				this.baseFormData.houseId = this.nfcId;
				
				return true;
			},
			
			// 防抖函数
			debounce1(fn, delay) {
				let timer;
				return function() {
					const _this = this;
					if (timer) {
						clearTimeout(timer);
						console.log('清楚了定时器', timer);
					}
					timer = setTimeout(function() {
						console.log('this的值', this);
						fn();
					}, delay);
					timer = null;
					console.log('创建了定时器', timer);
				};
			},
			
			// 处理点击事件
			async handleClick(cageId, num) {
				if (this.isSubmitting) {
					return;
				}
				
				this.isSubmitting = true;
				this.$loading();
				
				try {
					await this.checkDependencies();
					
					this.baseFormData.putNumber = num;
					this.baseFormData.cageId = cageId;
					this.baseFormData.putTime = getNowDate();
					this.cancel = true;
					
					console.log('点击参数:', { cageId, num });
					
					const data = await reqPutEggs(this.baseFormData);
					console.log('API响应:', data);
					
					if (data.code === 200) {
						this.cancel = false;
						
						// 更新状态
						const { siteId, houseId } = this.baseFormData;
						const obj = { siteId, houseId };
						await this.$store.dispatch('getStatu', obj);
						
						// 更新数据
						await this.getTips();
						await this.getStay();
						await this.getPR();
						
						this.$refs.uToast.show({
							title: `成功放入${num}个仔`,
							type: 'success',
							duration: '600',
							position: 'top'
						});
					} else if (data.code === 404) {
						this.$refs.uToast.show({
							title: data.msg,
							type: 'warning',
							duration: '800',
							position: 'top'
						});
					}
				} catch (error) {
					console.error('handleClick error:', error);
					this.$refs.uToast.show({
						title: '操作失败: ' + (error.message || '未知错误'),
						type: 'error',
						duration: '800',
						position: 'top'
					});
				} finally {
					this.$hide();
					this.isSubmitting = false;
				}
			},
			
			// 获取提示信息
			async getTips() {
				try {
					console.log('调用getTips成功', this.nfcId);
					
					await this.checkDependencies();
					
					const ids = {
						siteId: uni.getStorageSync('siteId'),
						houseId: this.nfcId
					};
					
					const data = await reqPutTips(ids);
					console.log('getTips响应:', data);
					
					if (data.code == 200) {
						console.log('tips in putEggs of getTips', data.stay);
						this.tip = format(data.stay.house_id, uni.getStorageSync('siteId'));
					} else if (data.code === 404) {
						this.$refs.uToast.show({
							title: data.msg,
							type: 'error',
							duration: '800',
							position: 'top'
						});
					}
				} catch (error) {
					console.error('getTips error:', error);
					throw error;
				} finally {
					uni.stopPullDownRefresh();
				}
			},
			
			// 获取停留数量
			async getStay() {
				try {
					await this.checkDependencies();
					
					const obj = {
						siteId: uni.getStorageSync('siteId'),
						houseId: this.nfcId
					};
					
					const res = await reqStayNum(obj);
					
					if (res.code === 200) {
						console.log('getStay响应:', res);
						// 修复：确保stayNum是数组
						this.stayNum = Array.isArray(res.cages) ? res.cages : [];
						console.log('设置stayNum:', this.stayNum);
					} else {
						this.$refs.uToast.show({
							title: res.msg || '获取数据失败',
							type: 'error',
							duration: '800',
							position: 'top'
						});
						// 修复：失败时设置为空数组
						this.stayNum = [];
					}
				} catch (error) {
					console.error('getStay error:', error);
					// 修复：错误时设置为空数组
					this.stayNum = [];
					throw error;
				}
			},
			
			// 获取当天的留窝抽蛋比例
			async getPR() {
				try {
					const siteId = uni.getStorageSync('siteId');
					if (!siteId) {
						throw new Error('站点ID不存在');
					}
					
					console.log('有site');
					const obj = {
						site_id: siteId
					};
					
					await this.$store.dispatch('getEWPR', obj);
				} catch (error) {
					console.error('getPR error:', error);
					throw error;
				}
			},
			
			toExp() {
				uni.navigateTo({
					url: '/pages/expection/expection'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'styles/builder.scss';

	.checked_border {
		background-color: #fff;
		color: lawngreen;
		border: 2px solid greenyellow;
	}

	.ycd_bg {
		background-color: #dbe2f1;
	}

	.ycd_color {
		color: #4472c4;
	}

	.ycd_color_left {
		color: #7d9ad2;
		border-right: 2px solid #7c9bd2;
	}

	.ycd_button_right {
		color: #dbe2f1;
		background-color: #7c9bd2;
	}

	.other_bg {
		background-color: #7c9bd2;
	}

	.other_color_left {
		color: #dbe2f1;
		border-right: 2px solid #dbe2f1;
	}

	.other_button_right {
		color: #7c9bd2;
		background-color: #dbe2f1;
	}

	.houseId {
		width: 100%;
		margin: 10rpx auto;
		padding: 18.12rpx 18.12rpx;
		font-size: 39.86rpx;
		border-radius: 14.49rpx;
		color: #fff;
		background-color: #7d9ad2;
	}

	.tip {
		font-weight: bold;
		padding-left: 10rpx;
		color: darkgray;

		span {
			color: gray;
			font-size: 36rpx;
		}
	}

	.circle {
		width: 100%;
		height: 100vh;

		h1 {
			text-align: center;
			font-weight: 700;
		}

		.ul {
		  display: flex;
		  /* 关键：改为横向排列 */
		  flex-direction: row; 
		  justify-content: space-around;
		  align-content: space-around;
		  width: 100%;
		  height: 70%;
		  flex-wrap: wrap; /* 保持换行 */
		  margin-top: 20rpx;
				
		.li {
		  display: flex;
		  justify-content: space-around;
		  /* 关键：宽度调整为 ~45%，确保一行两个 */
		  width: 45%; 
		  height: 30%;
		  text-align: center;
		  align-items: center;
		  border-radius: 20rpx;
		  background-color: #dbe2f1; /* 保留原有蓝色笼子背景 */
		  /* 其他原有样式（如边框、字体等）保持不变 */
		

				.left,
				.right {
					display: flex;
					flex-direction: column;
					justify-content: space-around;
					height: 90%;
					font-weight: bold;
				}

				.left {
					width: 33%;
					justify-content: center;
					border-right: 2px solid #7c9bd2;
					box-sizing: border-box;
					color: #4472c4;

					.cageId {
						font-size: 100rpx;
					}

					.statu {
						font-size: 20rpx;
					}
				}

				.right {
					width: 66%;
					display: flex;
					flex-direction: row;
					justify-content: space-around;
					align-content: space-around;
					flex-wrap: wrap;

					button {
						display: inline-block;
					}

					.num {
						@include flex(center, center, 'items');
						width: 40%;
						height: 40%;
						font-size: 41.16rpx;
						font-weight: bold;
						border-radius: 10rpx;
						box-sizing: border-box;
						border: 1px solid #7c9bd2;
						
						&:disabled {
							opacity: 0.6;
							pointer-events: none;
						}
					}

					.submit {
						width: 80%;
						font-size: 20rpx;
						font-weight: bold;
						border-radius: 10rpx;
					}
				}
			}
		}
		
		// 添加加载状态和无数据状态的样式
		.loading-data, .no-data {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 200rpx;
			font-size: 32rpx;
			color: #999;
			flex-direction: column;
			
			text {
				margin-top: 20rpx;
			}
		}
	}

	.abnormal {
		@include flex(space-around, center, 'items');
		width: 70%;
		height: 120rpx;
		margin: 0 auto;
		padding: 20rpx 57.97rpx;
		font-size: 38.04rpx;
		font-weight: 700;
		color: #fff;
		box-shadow: 9px 4px 10px 0 #7d9ad2;
		background-color: #7d9ad2;
	}

	@include responseTo('phone') {
		.circle .ul .li .left .statu {
			font-size: 36rpx;
		}
	}
</style>